blob: 5881f8c7a91069833c704c265d69b584f9bbe167 [file] [log] [blame]
Andreas Gampe319dbe82017-01-09 16:42:21 -08001/* Copyright (C) 2017 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_monitor.h"
33
34#include <atomic>
35#include <chrono>
36#include <condition_variable>
37#include <mutex>
38
39#include "art_jvmti.h"
Alex Light41006c62017-09-14 09:51:14 -070040#include "monitor.h"
Andreas Gampe319dbe82017-01-09 16:42:21 -080041#include "runtime.h"
42#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070043#include "thread-current-inl.h"
Alex Light23aa7482017-08-16 10:01:13 -070044#include "ti_thread.h"
Alex Light41006c62017-09-14 09:51:14 -070045#include "thread.h"
46#include "thread_pool.h"
Andreas Gampe319dbe82017-01-09 16:42:21 -080047
48namespace openjdkjvmti {
49
50// We cannot use ART monitors, as they require the mutator lock for contention locking. We
51// also cannot use pthread mutexes and condition variables (or C++11 abstractions) directly,
52// as the do not have the right semantics for recursive mutexes and waiting (wait only unlocks
53// the mutex once).
54// So go ahead and use a wrapper that does the counting explicitly.
55
56class JvmtiMonitor {
57 public:
Alex Light23aa7482017-08-16 10:01:13 -070058 JvmtiMonitor() : owner_(nullptr), count_(0) { }
Andreas Gampe319dbe82017-01-09 16:42:21 -080059
David Sehrae3bcac2017-02-03 15:19:00 -080060 static bool Destroy(art::Thread* self, JvmtiMonitor* monitor) NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampe319dbe82017-01-09 16:42:21 -080061 // Check whether this thread holds the monitor, or nobody does.
62 art::Thread* owner_thread = monitor->owner_.load(std::memory_order_relaxed);
63 if (owner_thread != nullptr && self != owner_thread) {
64 return false;
65 }
66
67 if (monitor->count_ > 0) {
68 monitor->count_ = 0;
69 monitor->owner_.store(nullptr, std::memory_order_relaxed);
70 monitor->mutex_.unlock();
71 }
72
73 delete monitor;
74 return true;
75 }
76
David Sehrae3bcac2017-02-03 15:19:00 -080077 void MonitorEnter(art::Thread* self) NO_THREAD_SAFETY_ANALYSIS {
Alex Light23aa7482017-08-16 10:01:13 -070078 // Perform a suspend-check. The spec doesn't require this but real-world agents depend on this
79 // behavior. We do this by performing a suspend-check then retrying if the thread is suspended
80 // before or after locking the internal mutex.
81 do {
82 ThreadUtil::SuspendCheck(self);
83 if (ThreadUtil::WouldSuspendForUserCode(self)) {
84 continue;
85 }
Andreas Gampe319dbe82017-01-09 16:42:21 -080086
Alex Light23aa7482017-08-16 10:01:13 -070087 // Check for recursive enter.
88 if (IsOwner(self)) {
89 count_++;
90 return;
91 }
92
93 // Checking for user-code suspension takes acquiring 2 art::Mutexes so we want to avoid doing
94 // that if possible. To avoid it we try to get the internal mutex without sleeping. If we do
95 // this we don't bother doing another suspend check since it can linearize after the lock.
96 if (mutex_.try_lock()) {
97 break;
98 } else {
99 // Lock with sleep. We will need to check for suspension after this to make sure that agents
100 // won't deadlock.
101 mutex_.lock();
102 if (!ThreadUtil::WouldSuspendForUserCode(self)) {
103 break;
104 } else {
105 // We got suspended in the middle of waiting for the mutex. We should release the mutex
106 // and try again so we can get it while not suspended. This lets some other
107 // (non-suspended) thread acquire the mutex in case it's waiting to wake us up.
108 mutex_.unlock();
109 continue;
110 }
111 }
112 } while (true);
Andreas Gampe319dbe82017-01-09 16:42:21 -0800113
114 DCHECK(owner_.load(std::memory_order_relaxed) == nullptr);
115 owner_.store(self, std::memory_order_relaxed);
116 DCHECK_EQ(0u, count_);
117 count_ = 1;
118 }
119
David Sehrae3bcac2017-02-03 15:19:00 -0800120 bool MonitorExit(art::Thread* self) NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampe319dbe82017-01-09 16:42:21 -0800121 if (!IsOwner(self)) {
122 return false;
123 }
124
125 --count_;
126 if (count_ == 0u) {
127 owner_.store(nullptr, std::memory_order_relaxed);
128 mutex_.unlock();
129 }
130
131 return true;
132 }
133
134 bool Wait(art::Thread* self) {
135 auto wait_without_timeout = [&](std::unique_lock<std::mutex>& lk) {
136 cond_.wait(lk);
137 };
138 return Wait(self, wait_without_timeout);
139 }
140
141 bool Wait(art::Thread* self, uint64_t timeout_in_ms) {
142 auto wait_with_timeout = [&](std::unique_lock<std::mutex>& lk) {
143 cond_.wait_for(lk, std::chrono::milliseconds(timeout_in_ms));
144 };
145 return Wait(self, wait_with_timeout);
146 }
147
148 bool Notify(art::Thread* self) {
149 return Notify(self, [&]() { cond_.notify_one(); });
150 }
151
152 bool NotifyAll(art::Thread* self) {
153 return Notify(self, [&]() { cond_.notify_all(); });
154 }
155
156 private:
Alex Light23aa7482017-08-16 10:01:13 -0700157 bool IsOwner(art::Thread* self) const {
Andreas Gampe319dbe82017-01-09 16:42:21 -0800158 // There's a subtle correctness argument here for a relaxed load outside the critical section.
159 // A thread is guaranteed to see either its own latest store or another thread's store. If a
160 // thread sees another thread's store than it cannot be holding the lock.
161 art::Thread* owner_thread = owner_.load(std::memory_order_relaxed);
162 return self == owner_thread;
163 }
164
165 template <typename T>
166 bool Wait(art::Thread* self, T how_to_wait) {
167 if (!IsOwner(self)) {
168 return false;
169 }
170
171 size_t old_count = count_;
172
173 count_ = 0;
174 owner_.store(nullptr, std::memory_order_relaxed);
175
176 {
177 std::unique_lock<std::mutex> lk(mutex_, std::adopt_lock);
178 how_to_wait(lk);
179 lk.release(); // Do not unlock the mutex.
180 }
181
182 DCHECK(owner_.load(std::memory_order_relaxed) == nullptr);
183 owner_.store(self, std::memory_order_relaxed);
184 DCHECK_EQ(0u, count_);
185 count_ = old_count;
186
187 return true;
188 }
189
190 template <typename T>
191 bool Notify(art::Thread* self, T how_to_notify) {
192 if (!IsOwner(self)) {
193 return false;
194 }
195
196 how_to_notify();
197
198 return true;
199 }
200
201 std::mutex mutex_;
202 std::condition_variable cond_;
203 std::atomic<art::Thread*> owner_;
204 size_t count_;
205};
206
207static jrawMonitorID EncodeMonitor(JvmtiMonitor* monitor) {
208 return reinterpret_cast<jrawMonitorID>(monitor);
209}
210
211static JvmtiMonitor* DecodeMonitor(jrawMonitorID id) {
212 return reinterpret_cast<JvmtiMonitor*>(id);
213}
214
215jvmtiError MonitorUtil::CreateRawMonitor(jvmtiEnv* env ATTRIBUTE_UNUSED,
216 const char* name,
217 jrawMonitorID* monitor_ptr) {
218 if (name == nullptr || monitor_ptr == nullptr) {
219 return ERR(NULL_POINTER);
220 }
221
222 JvmtiMonitor* monitor = new JvmtiMonitor();
223 *monitor_ptr = EncodeMonitor(monitor);
224
225 return ERR(NONE);
226}
227
228jvmtiError MonitorUtil::DestroyRawMonitor(jvmtiEnv* env ATTRIBUTE_UNUSED, jrawMonitorID id) {
229 if (id == nullptr) {
230 return ERR(INVALID_MONITOR);
231 }
232
233 JvmtiMonitor* monitor = DecodeMonitor(id);
234 art::Thread* self = art::Thread::Current();
235
236 if (!JvmtiMonitor::Destroy(self, monitor)) {
237 return ERR(NOT_MONITOR_OWNER);
238 }
239
240 return ERR(NONE);
241}
242
243jvmtiError MonitorUtil::RawMonitorEnter(jvmtiEnv* env ATTRIBUTE_UNUSED, jrawMonitorID id) {
244 if (id == nullptr) {
245 return ERR(INVALID_MONITOR);
246 }
247
248 JvmtiMonitor* monitor = DecodeMonitor(id);
249 art::Thread* self = art::Thread::Current();
250
251 monitor->MonitorEnter(self);
252
253 return ERR(NONE);
254}
255
256jvmtiError MonitorUtil::RawMonitorExit(jvmtiEnv* env ATTRIBUTE_UNUSED, jrawMonitorID id) {
257 if (id == nullptr) {
258 return ERR(INVALID_MONITOR);
259 }
260
261 JvmtiMonitor* monitor = DecodeMonitor(id);
262 art::Thread* self = art::Thread::Current();
263
264 if (!monitor->MonitorExit(self)) {
265 return ERR(NOT_MONITOR_OWNER);
266 }
267
268 return ERR(NONE);
269}
270
271jvmtiError MonitorUtil::RawMonitorWait(jvmtiEnv* env ATTRIBUTE_UNUSED,
272 jrawMonitorID id,
273 jlong millis) {
274 if (id == nullptr) {
275 return ERR(INVALID_MONITOR);
276 }
277
278 JvmtiMonitor* monitor = DecodeMonitor(id);
279 art::Thread* self = art::Thread::Current();
280
Alex Light6ced0912017-08-16 15:16:13 -0700281 // What millis < 0 means is not defined in the spec. Real world agents seem to assume that it is a
282 // valid call though. We treat it as though it was 0 and wait indefinitely.
Andreas Gampe319dbe82017-01-09 16:42:21 -0800283 bool result = (millis > 0)
284 ? monitor->Wait(self, static_cast<uint64_t>(millis))
285 : monitor->Wait(self);
286
287 if (!result) {
288 return ERR(NOT_MONITOR_OWNER);
289 }
290
291 // TODO: Make sure that is really what we should be checking here.
292 if (self->IsInterrupted()) {
293 return ERR(INTERRUPT);
294 }
295
296 return ERR(NONE);
297}
298
299jvmtiError MonitorUtil::RawMonitorNotify(jvmtiEnv* env ATTRIBUTE_UNUSED, jrawMonitorID id) {
300 if (id == nullptr) {
301 return ERR(INVALID_MONITOR);
302 }
303
304 JvmtiMonitor* monitor = DecodeMonitor(id);
305 art::Thread* self = art::Thread::Current();
306
307 if (!monitor->Notify(self)) {
308 return ERR(NOT_MONITOR_OWNER);
309 }
310
311 return ERR(NONE);
312}
313
314jvmtiError MonitorUtil::RawMonitorNotifyAll(jvmtiEnv* env ATTRIBUTE_UNUSED, jrawMonitorID id) {
315 if (id == nullptr) {
316 return ERR(INVALID_MONITOR);
317 }
318
319 JvmtiMonitor* monitor = DecodeMonitor(id);
320 art::Thread* self = art::Thread::Current();
321
322 if (!monitor->NotifyAll(self)) {
323 return ERR(NOT_MONITOR_OWNER);
324 }
325
326 return ERR(NONE);
327}
328
Alex Light41006c62017-09-14 09:51:14 -0700329jvmtiError MonitorUtil::GetCurrentContendedMonitor(jvmtiEnv* env ATTRIBUTE_UNUSED,
330 jthread thread,
331 jobject* monitor) {
332 if (monitor == nullptr) {
333 return ERR(NULL_POINTER);
334 }
335 art::Thread* self = art::Thread::Current();
336 art::ScopedObjectAccess soa(self);
Alex Lightb1e31a82017-10-04 16:57:36 -0700337 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light7ddc23d2017-09-22 15:33:41 -0700338 art::Thread* target = nullptr;
339 jvmtiError err = ERR(INTERNAL);
340 if (!ThreadUtil::GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700341 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light7ddc23d2017-09-22 15:33:41 -0700342 return err;
Alex Light41006c62017-09-14 09:51:14 -0700343 }
344 struct GetContendedMonitorClosure : public art::Closure {
345 public:
346 explicit GetContendedMonitorClosure(art::Thread* current, jobject* out)
347 : result_thread_(current), out_(out) {}
348
349 void Run(art::Thread* target_thread) REQUIRES_SHARED(art::Locks::mutator_lock_) {
350 switch (target_thread->GetState()) {
351 // These three we are actually currently waiting on a monitor and have sent the appropriate
352 // events (if anyone is listening).
353 case art::kBlocked:
354 case art::kTimedWaiting:
355 case art::kWaiting: {
356 art::mirror::Object* mon = art::Monitor::GetContendedMonitor(target_thread);
357 *out_ = (mon == nullptr) ? nullptr
358 : result_thread_->GetJniEnv()->AddLocalReference<jobject>(mon);
359 return;
360 }
361 case art::kTerminated:
362 case art::kRunnable:
363 case art::kSleeping:
364 case art::kWaitingForLockInflation:
365 case art::kWaitingForTaskProcessor:
366 case art::kWaitingForGcToComplete:
367 case art::kWaitingForCheckPointsToRun:
368 case art::kWaitingPerformingGc:
369 case art::kWaitingForDebuggerSend:
370 case art::kWaitingForDebuggerToAttach:
371 case art::kWaitingInMainDebuggerLoop:
372 case art::kWaitingForDebuggerSuspension:
373 case art::kWaitingForJniOnLoad:
374 case art::kWaitingForSignalCatcherOutput:
375 case art::kWaitingInMainSignalCatcherLoop:
376 case art::kWaitingForDeoptimization:
377 case art::kWaitingForMethodTracingStart:
378 case art::kWaitingForVisitObjects:
379 case art::kWaitingForGetObjectsAllocated:
380 case art::kWaitingWeakGcRootRead:
381 case art::kWaitingForGcThreadFlip:
382 case art::kStarting:
383 case art::kNative:
384 case art::kSuspended: {
385 // We aren't currently (explicitly) waiting for a monitor anything so just return null.
386 *out_ = nullptr;
387 return;
388 }
389 }
390 }
391
392 private:
393 art::Thread* result_thread_;
394 jobject* out_;
395 };
396 GetContendedMonitorClosure closure(self, monitor);
Alex Lightb1e31a82017-10-04 16:57:36 -0700397 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light7ddc23d2017-09-22 15:33:41 -0700398 if (!target->RequestSynchronousCheckpoint(&closure)) {
399 return ERR(THREAD_NOT_ALIVE);
400 }
Alex Light41006c62017-09-14 09:51:14 -0700401 return OK;
402}
403
Andreas Gampe319dbe82017-01-09 16:42:21 -0800404} // namespace openjdkjvmti