blob: cabf9e8b0908f167e3c996c17bafdbbd71b87049 [file] [log] [blame]
Andreas Gampeaf13ab92017-01-11 20:57:40 -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_thread.h"
33
Andreas Gampe57943812017-12-06 21:39:13 -080034#include <android-base/logging.h>
35#include <android-base/strings.h>
36
Andreas Gampea1d2f952017-04-20 22:53:58 -070037#include "art_field-inl.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080038#include "art_jvmti.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080039#include "base/mutex.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080040#include "events-inl.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080041#include "gc/system_weak.h"
Alex Lightd9aff132017-10-31 22:30:05 +000042#include "gc/collector_type.h"
43#include "gc/gc_cause.h"
44#include "gc/scoped_gc_critical_section.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080045#include "gc_root-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010046#include "jni/jni_internal.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080047#include "mirror/class.h"
48#include "mirror/object-inl.h"
49#include "mirror/string.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070050#include "nativehelper/scoped_local_ref.h"
Alex Light93112972017-11-13 10:38:59 -080051#include "nativehelper/scoped_utf_chars.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080052#include "obj_ptr.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080053#include "runtime.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080054#include "runtime_callbacks.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080055#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070056#include "thread-current-inl.h"
Andreas Gampe85807442017-01-13 14:40:58 -080057#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070058#include "ti_phase.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080059#include "well_known_classes.h"
60
61namespace openjdkjvmti {
62
Andreas Gampedb6c2ab2017-03-28 17:28:32 -070063art::ArtField* ThreadUtil::context_class_loader_ = nullptr;
64
Alex Light1d8a9742017-08-17 11:12:06 -070065struct ThreadCallback : public art::ThreadLifecycleCallback {
Andreas Gampeeafaf572017-01-20 12:34:15 -080066 jthread GetThreadObject(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
67 if (self->GetPeer() == nullptr) {
68 return nullptr;
69 }
70 return self->GetJniEnv()->AddLocalReference<jthread>(self->GetPeer());
71 }
Alex Light1d8a9742017-08-17 11:12:06 -070072
Andreas Gampe983c1752017-01-23 19:46:56 -080073 template <ArtJvmtiEvent kEvent>
74 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -080075 DCHECK_EQ(self, art::Thread::Current());
76 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
Andreas Gampee6377462017-01-20 17:37:50 -080077 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -080078 event_handler->DispatchEvent<kEvent>(self,
79 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
80 thread.get());
Andreas Gampeeafaf572017-01-20 12:34:15 -080081 }
82
83 void ThreadStart(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
84 if (!started) {
85 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
86 // started here.
87 if (art::kIsDebugBuild) {
88 std::string name;
89 self->GetThreadName(name);
Alex Light5bd09542017-02-09 16:01:32 -080090 if (name != "JDWP" &&
91 name != "Signal Catcher" &&
92 !android::base::StartsWith(name, "Jit thread pool")) {
Alex Light23aa7482017-08-16 10:01:13 -070093 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
94 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -080095 }
96 }
97 return;
98 }
Andreas Gampe983c1752017-01-23 19:46:56 -080099 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800100 }
101
102 void ThreadDeath(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -0800103 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800104 }
105
Andreas Gampeeafaf572017-01-20 12:34:15 -0800106 EventHandler* event_handler = nullptr;
107 bool started = false;
108};
109
110ThreadCallback gThreadCallback;
111
112void ThreadUtil::Register(EventHandler* handler) {
113 art::Runtime* runtime = art::Runtime::Current();
114
115 gThreadCallback.started = runtime->IsStarted();
116 gThreadCallback.event_handler = handler;
117
118 art::ScopedThreadStateChange stsc(art::Thread::Current(),
119 art::ThreadState::kWaitingForDebuggerToAttach);
120 art::ScopedSuspendAll ssa("Add thread callback");
121 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
Alex Light1d8a9742017-08-17 11:12:06 -0700122}
123
124void ThreadUtil::VMInitEventSent() {
125 // We should have already started.
126 DCHECK(gThreadCallback.started);
127 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
128 // reported until Init.
129 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800130}
131
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700132void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700133 // We must have started since it is now safe to cache our data;
134 gThreadCallback.started = true;
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700135 art::ScopedObjectAccess soa(art::Thread::Current());
136 art::ObjPtr<art::mirror::Class> thread_class =
137 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
138 CHECK(thread_class != nullptr);
139 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
140 "Ljava/lang/ClassLoader;");
141 CHECK(context_class_loader_ != nullptr);
142}
143
Andreas Gampeeafaf572017-01-20 12:34:15 -0800144void ThreadUtil::Unregister() {
145 art::ScopedThreadStateChange stsc(art::Thread::Current(),
146 art::ThreadState::kWaitingForDebuggerToAttach);
147 art::ScopedSuspendAll ssa("Remove thread callback");
148 art::Runtime* runtime = art::Runtime::Current();
149 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800150}
151
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800152jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
153 art::Thread* self = art::Thread::Current();
154
155 art::ScopedObjectAccess soa(self);
156
157 jthread thread_peer;
158 if (self->IsStillStarting()) {
159 thread_peer = nullptr;
160 } else {
161 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
162 }
163
164 *thread_ptr = thread_peer;
165 return ERR(NONE);
166}
167
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800168// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700169bool ThreadUtil::GetNativeThread(jthread thread,
170 const art::ScopedObjectAccessAlreadyRunnable& soa,
171 /*out*/ art::Thread** thr,
172 /*out*/ jvmtiError* err) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800173 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700174 *thr = art::Thread::Current();
175 return true;
176 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
177 *err = ERR(INVALID_THREAD);
178 return false;
179 } else {
180 *thr = art::Thread::FromManagedThread(soa, thread);
181 return true;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800182 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700183}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800184
Alex Light7ddc23d2017-09-22 15:33:41 -0700185bool ThreadUtil::GetAliveNativeThread(jthread thread,
186 const art::ScopedObjectAccessAlreadyRunnable& soa,
187 /*out*/ art::Thread** thr,
188 /*out*/ jvmtiError* err) {
189 if (!GetNativeThread(thread, soa, thr, err)) {
190 return false;
191 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
192 *err = ERR(THREAD_NOT_ALIVE);
193 return false;
194 } else {
195 return true;
196 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800197}
198
199jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
200 if (info_ptr == nullptr) {
201 return ERR(NULL_POINTER);
202 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700203 if (!PhaseUtil::IsLivePhase()) {
204 return JVMTI_ERROR_WRONG_PHASE;
205 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800206
Alex Light3ae82532017-07-26 13:59:07 -0700207 art::Thread* self = art::Thread::Current();
208 art::ScopedObjectAccess soa(self);
209 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800210
Alex Light7ddc23d2017-09-22 15:33:41 -0700211 art::Thread* target;
212 jvmtiError err = ERR(INTERNAL);
213 if (!GetNativeThread(thread, soa, &target, &err)) {
214 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800215 }
216
Andreas Gampe54711412017-02-21 12:41:43 -0800217 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700218 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800219 // Have a native thread object, this thread is alive.
220 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700221 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800222 jvmtiError name_result;
223 name_uptr = CopyString(env, name.c_str(), &name_result);
224 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800225 return name_result;
226 }
Andreas Gampe54711412017-02-21 12:41:43 -0800227 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800228
Alex Light3ae82532017-07-26 13:59:07 -0700229 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800230
Alex Light3ae82532017-07-26 13:59:07 -0700231 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800232
Alex Light3ae82532017-07-26 13:59:07 -0700233 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800234
235 // ThreadGroup.
236 if (peer != nullptr) {
237 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
238 CHECK(f != nullptr);
239 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
240 info_ptr->thread_group = group == nullptr
241 ? nullptr
242 : soa.AddLocalReference<jthreadGroup>(group);
243 } else {
244 info_ptr->thread_group = nullptr;
245 }
246
247 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700248 DCHECK(context_class_loader_ != nullptr);
249 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
250 ? context_class_loader_->GetObject(peer)
251 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800252 info_ptr->context_class_loader = ccl == nullptr
253 ? nullptr
254 : soa.AddLocalReference<jobject>(ccl);
255 } else {
256 // Only the peer. This thread has either not been started, or is dead. Read things from
257 // the Java side.
258 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
259
260 // Name.
261 {
262 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
263 CHECK(f != nullptr);
264 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
265 std::string name_cpp;
266 const char* name_cstr;
267 if (name != nullptr) {
268 name_cpp = name->AsString()->ToModifiedUtf8();
269 name_cstr = name_cpp.c_str();
270 } else {
271 name_cstr = "";
272 }
Andreas Gampe54711412017-02-21 12:41:43 -0800273 jvmtiError name_result;
274 name_uptr = CopyString(env, name_cstr, &name_result);
275 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800276 return name_result;
277 }
Andreas Gampe54711412017-02-21 12:41:43 -0800278 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800279 }
280
281 // Priority.
282 {
283 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
284 CHECK(f != nullptr);
285 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
286 }
287
288 // Daemon.
289 {
290 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
291 CHECK(f != nullptr);
292 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
293 }
294
295 // ThreadGroup.
296 {
297 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
298 CHECK(f != nullptr);
299 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
300 info_ptr->thread_group = group == nullptr
301 ? nullptr
302 : soa.AddLocalReference<jthreadGroup>(group);
303 }
304
305 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700306 DCHECK(context_class_loader_ != nullptr);
307 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
308 ? context_class_loader_->GetObject(peer)
309 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800310 info_ptr->context_class_loader = ccl == nullptr
311 ? nullptr
312 : soa.AddLocalReference<jobject>(ccl);
313 }
314
315 name_uptr.release();
316
317 return ERR(NONE);
318}
319
Alex Light1f0a22f2017-07-17 12:55:59 -0700320struct InternalThreadState {
321 art::Thread* native_thread;
322 art::ThreadState art_state;
323 int thread_user_code_suspend_count;
324};
325
326// Return the thread's (or current thread, if null) thread state.
Alex Light7ddc23d2017-09-22 15:33:41 -0700327static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700328 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700329 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700330 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700331 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
332 thread_state.native_thread = target;
333 if (target == nullptr || target->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700334 thread_state.art_state = art::ThreadState::kStarting;
335 thread_state.thread_user_code_suspend_count = 0;
336 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700337 thread_state.art_state = target->GetState();
338 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800339 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700340 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800341}
342
Alex Light1f0a22f2017-07-17 12:55:59 -0700343static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
344 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800345 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
346
Alex Light1f0a22f2017-07-17 12:55:59 -0700347 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700348 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
349 // kSuspended state it will move to that once it hits a checkpoint so we can still set this.
Andreas Gampe72c19832017-01-12 13:22:16 -0800350 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
351 // Note: We do not have data about the previous state. Otherwise we should load the previous
352 // state here.
353 }
354
Alex Light1f0a22f2017-07-17 12:55:59 -0700355 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700356 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700357 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
358 }
359
Alex Light597adad2017-10-16 16:11:42 -0700360 // Enumerate all the thread states and fill in the other bits. This contains the results of
361 // following the decision tree in the JVMTI spec GetThreadState documentation.
362 switch (internal_thread_state) {
363 case art::ThreadState::kRunnable:
364 case art::ThreadState::kWaitingWeakGcRootRead:
365 case art::ThreadState::kSuspended:
366 // These are all simply runnable.
367 // kRunnable is self-explanatory.
368 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
369 // so we want to keep it marked as runnable.
370 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
371 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
372 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
373 break;
374 case art::ThreadState::kNative:
375 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
376 // state but we don't have the information to know if it should be present for any but the
377 // kNative state.
378 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
379 JVMTI_THREAD_STATE_RUNNABLE);
380 break;
381 case art::ThreadState::kBlocked:
382 // Blocked is one of the top level states so it sits alone.
383 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
384 break;
385 case art::ThreadState::kWaiting:
386 // Object.wait() so waiting, indefinitely, in object.wait.
387 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
388 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
389 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
390 break;
391 case art::ThreadState::kTimedWaiting:
392 // Object.wait(long) so waiting, with timeout, in object.wait.
393 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
394 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
395 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
396 break;
397 case art::ThreadState::kSleeping:
398 // In object.sleep. This is a timed wait caused by sleep.
399 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
400 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
401 JVMTI_THREAD_STATE_SLEEPING);
402 break;
403 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
404 // attached.
405 case art::ThreadState::kWaitingForDebuggerSend:
406 case art::ThreadState::kWaitingForDebuggerToAttach:
407 case art::ThreadState::kWaitingInMainDebuggerLoop:
408 case art::ThreadState::kWaitingForDebuggerSuspension:
409 case art::ThreadState::kWaitingForLockInflation:
410 case art::ThreadState::kWaitingForTaskProcessor:
411 case art::ThreadState::kWaitingForGcToComplete:
412 case art::ThreadState::kWaitingForCheckPointsToRun:
413 case art::ThreadState::kWaitingPerformingGc:
414 case art::ThreadState::kWaitingForJniOnLoad:
415 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
416 case art::ThreadState::kWaitingForSignalCatcherOutput:
417 case art::ThreadState::kWaitingForDeoptimization:
418 case art::ThreadState::kWaitingForMethodTracingStart:
419 case art::ThreadState::kWaitingForVisitObjects:
420 case art::ThreadState::kWaitingForGetObjectsAllocated:
421 case art::ThreadState::kWaitingForGcThreadFlip:
422 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
423 // caused by sleep, park, or object#wait.
424 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
425 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
426 break;
427 case art::ThreadState::kStarting:
428 case art::ThreadState::kTerminated:
429 // We only call this if we are alive so we shouldn't see either of these states.
430 LOG(FATAL) << "Should not be in state " << internal_thread_state;
431 UNREACHABLE();
Andreas Gampe72c19832017-01-12 13:22:16 -0800432 }
Alex Light597adad2017-10-16 16:11:42 -0700433 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800434
435 return jvmti_state;
436}
437
Alex Light1f0a22f2017-07-17 12:55:59 -0700438static jint GetJavaStateFromInternal(const InternalThreadState& state) {
439 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800440 case art::ThreadState::kTerminated:
441 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
442
443 case art::ThreadState::kRunnable:
444 case art::ThreadState::kNative:
445 case art::ThreadState::kWaitingWeakGcRootRead:
446 case art::ThreadState::kSuspended:
447 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
448
449 case art::ThreadState::kTimedWaiting:
450 case art::ThreadState::kSleeping:
451 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
452
453 case art::ThreadState::kBlocked:
454 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
455
456 case art::ThreadState::kStarting:
457 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
458
459 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700460 case art::ThreadState::kWaitingForTaskProcessor:
461 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800462 case art::ThreadState::kWaitingForGcToComplete:
463 case art::ThreadState::kWaitingPerformingGc:
464 case art::ThreadState::kWaitingForCheckPointsToRun:
465 case art::ThreadState::kWaitingForDebuggerSend:
466 case art::ThreadState::kWaitingForDebuggerToAttach:
467 case art::ThreadState::kWaitingInMainDebuggerLoop:
468 case art::ThreadState::kWaitingForDebuggerSuspension:
469 case art::ThreadState::kWaitingForDeoptimization:
470 case art::ThreadState::kWaitingForGetObjectsAllocated:
471 case art::ThreadState::kWaitingForJniOnLoad:
472 case art::ThreadState::kWaitingForSignalCatcherOutput:
473 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
474 case art::ThreadState::kWaitingForMethodTracingStart:
475 case art::ThreadState::kWaitingForVisitObjects:
476 case art::ThreadState::kWaitingForGcThreadFlip:
477 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
478 }
479 LOG(FATAL) << "Unreachable";
480 UNREACHABLE();
481}
482
Alex Light1f0a22f2017-07-17 12:55:59 -0700483// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700484void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700485 art::ScopedObjectAccess soa(self);
486 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
487 self->FullSuspendCheck();
488}
489
Alex Light23aa7482017-08-16 10:01:13 -0700490bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
491 DCHECK(self == art::Thread::Current());
492 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
493 return self->GetUserCodeSuspendCount() != 0;
494}
495
496bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
497 DCHECK(self == art::Thread::Current());
498 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
499 return WouldSuspendForUserCodeLocked(self);
500}
501
Andreas Gampe72c19832017-01-12 13:22:16 -0800502jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
503 jthread thread,
504 jint* thread_state_ptr) {
505 if (thread_state_ptr == nullptr) {
506 return ERR(NULL_POINTER);
507 }
508
Alex Light1f0a22f2017-07-17 12:55:59 -0700509 art::Thread* self = art::Thread::Current();
510 InternalThreadState state = {};
511 // Loop since we need to bail out and try again if we would end up getting suspended while holding
512 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
513 // release the lock, wait to get resumed and try again.
514 do {
515 SuspendCheck(self);
516 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700517 if (WouldSuspendForUserCodeLocked(self)) {
518 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
519 // a user-code suspension. We retry and do another SuspendCheck to clear this.
520 continue;
Alex Light1f0a22f2017-07-17 12:55:59 -0700521 }
522 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700523 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700524 jvmtiError err = ERR(INTERNAL);
525 art::Thread* target = nullptr;
526 if (!GetNativeThread(thread, soa, &target, &err)) {
527 return err;
528 }
529 state = GetNativeThreadState(target);
Alex Light3ae82532017-07-26 13:59:07 -0700530 if (state.art_state == art::ThreadState::kStarting) {
531 break;
532 }
533 DCHECK(state.native_thread != nullptr);
534
535 // Translate internal thread state to JVMTI and Java state.
536 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
537
538 // Java state is derived from nativeGetState.
539 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
540 // different mask if a thread got suspended due to user-code. However, this is for
541 // consistency with the Java view.
542 jint java_state = GetJavaStateFromInternal(state);
543
544 *thread_state_ptr = jvmti_state | java_state;
545
546 return ERR(NONE);
Alex Light1f0a22f2017-07-17 12:55:59 -0700547 } while (true);
Andreas Gampe72c19832017-01-12 13:22:16 -0800548
Alex Light3ae82532017-07-26 13:59:07 -0700549 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800550
Alex Light3ae82532017-07-26 13:59:07 -0700551 if (thread == nullptr) {
552 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
553 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800554 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800555
Alex Light3ae82532017-07-26 13:59:07 -0700556 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700557 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800558
Alex Light3ae82532017-07-26 13:59:07 -0700559 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700560 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
561 art::ObjPtr<art::mirror::Class> thread_klass =
562 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
563 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
564 return ERR(INVALID_THREAD);
565 }
566 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700567 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700568 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700569 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
570 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
571 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
572 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800573 return ERR(NONE);
574}
575
Andreas Gampe85807442017-01-13 14:40:58 -0800576jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
577 jint* threads_count_ptr,
578 jthread** threads_ptr) {
579 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
580 return ERR(NULL_POINTER);
581 }
582
583 art::Thread* current = art::Thread::Current();
584
585 art::ScopedObjectAccess soa(current);
586
587 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
588 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
589
590 std::vector<art::ObjPtr<art::mirror::Object>> peers;
591
592 for (art::Thread* thread : thread_list) {
593 // Skip threads that are still starting.
594 if (thread->IsStillStarting()) {
595 continue;
596 }
597
Andreas Gampe202f85a2017-02-06 10:23:26 -0800598 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800599 if (peer != nullptr) {
600 peers.push_back(peer);
601 }
602 }
603
604 if (peers.empty()) {
605 *threads_count_ptr = 0;
606 *threads_ptr = nullptr;
607 } else {
608 unsigned char* data;
609 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
610 if (data_result != ERR(NONE)) {
611 return data_result;
612 }
613 jthread* threads = reinterpret_cast<jthread*>(data);
614 for (size_t i = 0; i != peers.size(); ++i) {
615 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
616 }
617
618 *threads_count_ptr = static_cast<jint>(peers.size());
619 *threads_ptr = threads;
620 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800621 return ERR(NONE);
622}
Andreas Gampe85807442017-01-13 14:40:58 -0800623
Alex Light092a4042017-07-12 08:46:44 -0700624// The struct that we store in the art::Thread::custom_tls_ that maps the jvmtiEnvs to the data
625// stored with that thread. This is needed since different jvmtiEnvs are not supposed to share TLS
626// data but we only have a single slot in Thread objects to store data.
627struct JvmtiGlobalTLSData {
628 std::unordered_map<jvmtiEnv*, const void*> data GUARDED_BY(art::Locks::thread_list_lock_);
629};
630
631static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
632 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
633 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
634 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
635 if (global_tls != nullptr) {
636 global_tls->data.erase(env);
637 }
638}
639
640void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
641 art::Thread* self = art::Thread::Current();
642 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
643 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
644 list->ForEach(RemoveTLSData, env);
645}
646
647jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
648 art::Thread* self = art::Thread::Current();
649 art::ScopedObjectAccess soa(self);
650 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700651 art::Thread* target = nullptr;
652 jvmtiError err = ERR(INTERNAL);
653 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
654 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800655 }
656
Alex Light092a4042017-07-12 08:46:44 -0700657 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
658 if (global_tls == nullptr) {
659 target->SetCustomTLS(new JvmtiGlobalTLSData);
660 global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
661 }
662
663 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800664
665 return ERR(NONE);
666}
667
Alex Light092a4042017-07-12 08:46:44 -0700668jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800669 jthread thread,
670 void** data_ptr) {
671 if (data_ptr == nullptr) {
672 return ERR(NULL_POINTER);
673 }
674
Alex Light092a4042017-07-12 08:46:44 -0700675 art::Thread* self = art::Thread::Current();
676 art::ScopedObjectAccess soa(self);
677 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700678 art::Thread* target = nullptr;
679 jvmtiError err = ERR(INTERNAL);
680 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
681 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800682 }
683
Alex Light092a4042017-07-12 08:46:44 -0700684 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
685 if (global_tls == nullptr) {
686 *data_ptr = nullptr;
687 return OK;
688 }
689 auto it = global_tls->data.find(env);
690 if (it != global_tls->data.end()) {
691 *data_ptr = const_cast<void*>(it->second);
692 } else {
693 *data_ptr = nullptr;
694 }
695
Andreas Gampe85807442017-01-13 14:40:58 -0800696 return ERR(NONE);
697}
698
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800699struct AgentData {
700 const void* arg;
701 jvmtiStartFunction proc;
702 jthread thread;
703 JavaVM* java_vm;
704 jvmtiEnv* jvmti_env;
705 jint priority;
Alex Light93112972017-11-13 10:38:59 -0800706 std::string name;
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800707};
708
709static void* AgentCallback(void* arg) {
710 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
711 CHECK(data->thread != nullptr);
712
713 // We already have a peer. So call our special Attach function.
Alex Light93112972017-11-13 10:38:59 -0800714 art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
Alex Light739bf722017-10-20 13:14:24 -0700715 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800716 // The name in Attach() is only for logging. Set the thread name. This is important so
717 // that the thread is no longer seen as starting up.
718 {
719 art::ScopedObjectAccess soa(self);
Alex Light93112972017-11-13 10:38:59 -0800720 self->SetThreadName(data->name.c_str());
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800721 }
722
723 // Release the peer.
724 JNIEnv* env = self->GetJniEnv();
725 env->DeleteGlobalRef(data->thread);
726 data->thread = nullptr;
727
Alex Light739bf722017-10-20 13:14:24 -0700728 {
729 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
730 // before going into the provided code.
731 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
732 art::Runtime::Current()->EndThreadBirth();
733 }
734
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800735 // Run the agent code.
736 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
737
738 // Detach the thread.
739 int detach_result = data->java_vm->DetachCurrentThread();
740 CHECK_EQ(detach_result, 0);
741
742 return nullptr;
743}
744
745jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
746 jthread thread,
747 jvmtiStartFunction proc,
748 const void* arg,
749 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700750 if (!PhaseUtil::IsLivePhase()) {
751 return ERR(WRONG_PHASE);
752 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800753 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
754 return ERR(INVALID_PRIORITY);
755 }
756 JNIEnv* env = art::Thread::Current()->GetJniEnv();
757 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
758 return ERR(INVALID_THREAD);
759 }
760 if (proc == nullptr) {
761 return ERR(NULL_POINTER);
762 }
763
Alex Light739bf722017-10-20 13:14:24 -0700764 {
765 art::Runtime* runtime = art::Runtime::Current();
766 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
767 if (runtime->IsShuttingDownLocked()) {
768 // The runtime is shutting down so we cannot create new threads.
769 // TODO It's not fully clear from the spec what we should do here. We aren't yet in
770 // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
771 // impossible. Existing agents don't seem to generally do anything with this return value so
772 // it doesn't matter too much. We could do something like sending a fake ThreadStart event
773 // even though code is never actually run.
774 return ERR(INTERNAL);
775 }
776 runtime->StartThreadBirth();
777 }
778
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800779 std::unique_ptr<AgentData> data(new AgentData);
780 data->arg = arg;
781 data->proc = proc;
782 // We need a global ref for Java objects, as local refs will be invalid.
783 data->thread = env->NewGlobalRef(thread);
784 data->java_vm = art::Runtime::Current()->GetJavaVM();
785 data->jvmti_env = jvmti_env;
786 data->priority = priority;
Alex Light93112972017-11-13 10:38:59 -0800787 ScopedLocalRef<jstring> s(
788 env,
789 reinterpret_cast<jstring>(
790 env->GetObjectField(thread, art::WellKnownClasses::java_lang_Thread_name)));
791 if (s == nullptr) {
792 data->name = "JVMTI Agent Thread";
793 } else {
794 ScopedUtfChars name(env, s.get());
795 data->name = name.c_str();
796 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800797
798 pthread_t pthread;
799 int pthread_create_result = pthread_create(&pthread,
Alex Light739bf722017-10-20 13:14:24 -0700800 nullptr,
801 &AgentCallback,
802 reinterpret_cast<void*>(data.get()));
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800803 if (pthread_create_result != 0) {
Alex Light739bf722017-10-20 13:14:24 -0700804 // If the create succeeded the other thread will call EndThreadBirth.
805 art::Runtime* runtime = art::Runtime::Current();
806 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
807 runtime->EndThreadBirth();
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800808 return ERR(INTERNAL);
809 }
810 data.release();
811
812 return ERR(NONE);
813}
814
Alex Light88fd7202017-06-30 08:31:59 -0700815jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700816 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700817 // Loop since we need to bail out and try again if we would end up getting suspended while holding
818 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
819 // release the lock, wait to get resumed and try again.
820 do {
821 // Suspend ourself if we have any outstanding suspends. This is so we won't suspend due to
822 // another SuspendThread in the middle of suspending something else potentially causing a
823 // deadlock. We need to do this in the loop because if we ended up back here then we had
824 // outstanding SuspendReason::kForUserCode suspensions and we should wait for them to be cleared
825 // before continuing.
826 SuspendCheck(self);
827 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700828 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light88fd7202017-06-30 08:31:59 -0700829 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
830 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700831 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700832 }
Alex Light23aa7482017-08-16 10:01:13 -0700833 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700834 {
835 art::ScopedObjectAccess soa(self);
836 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700837 art::Thread* target = nullptr;
838 jvmtiError err = ERR(INTERNAL);
839 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
840 return err;
841 }
Alex Light88fd7202017-06-30 08:31:59 -0700842 art::ThreadState state = target->GetState();
Alex Light7ddc23d2017-09-22 15:33:41 -0700843 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Light88fd7202017-06-30 08:31:59 -0700844 return ERR(THREAD_NOT_ALIVE);
Alex Light3ae82532017-07-26 13:59:07 -0700845 } else {
846 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
847 if (target->GetUserCodeSuspendCount() != 0) {
848 return ERR(THREAD_SUSPENDED);
849 }
Alex Light88fd7202017-06-30 08:31:59 -0700850 }
851 }
Alex Light3ae82532017-07-26 13:59:07 -0700852 bool timeout = true;
853 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
854 target_jthread,
855 /* request_suspension */ true,
856 art::SuspendReason::kForUserCode,
857 &timeout);
858 if (ret_target == nullptr && !timeout) {
859 // TODO It would be good to get more information about why exactly the thread failed to
860 // suspend.
861 return ERR(INTERNAL);
862 } else if (!timeout) {
863 // we didn't time out and got a result.
864 return OK;
865 }
866 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700867 } while (true);
868 UNREACHABLE();
869}
870
871jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
872 CHECK(self == art::Thread::Current());
873 {
874 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
875 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
876 if (self->GetUserCodeSuspendCount() != 0) {
877 // This can only happen if we race with another thread to suspend 'self' and we lose.
878 return ERR(THREAD_SUSPENDED);
879 }
880 // We shouldn't be able to fail this.
881 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
882 // TODO More specific error would be nice.
883 return ERR(INTERNAL);
884 }
885 }
886 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
887 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
888 // to go to sleep until we are resumed.
889 SuspendCheck(self);
890 return OK;
891}
892
893jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
894 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700895 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700896 {
897 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700898 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700899 art::Thread* target = nullptr;
900 jvmtiError err = ERR(INTERNAL);
901 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
902 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700903 } else if (target == self) {
904 target_is_self = true;
905 }
Alex Light88fd7202017-06-30 08:31:59 -0700906 }
Alex Light3ae82532017-07-26 13:59:07 -0700907 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700908 return SuspendSelf(self);
909 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700910 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700911 }
912}
913
914jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
915 jthread thread) {
916 if (thread == nullptr) {
917 return ERR(NULL_POINTER);
918 }
919 art::Thread* self = art::Thread::Current();
920 art::Thread* target;
Alex Light3ae82532017-07-26 13:59:07 -0700921 // Retry until we know we won't get suspended by user code while resuming something.
922 do {
923 SuspendCheck(self);
924 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700925 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light3ae82532017-07-26 13:59:07 -0700926 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
927 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700928 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700929 }
Alex Light3ae82532017-07-26 13:59:07 -0700930 // From now on we know we cannot get suspended by user-code.
931 {
932 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
933 // have the 'suspend_lock' locked here.
934 art::ScopedObjectAccess soa(self);
935 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700936 jvmtiError err = ERR(INTERNAL);
937 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
938 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700939 } else if (target == self) {
940 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
941 // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
942 // about current state since it's all concurrent.
943 return ERR(THREAD_NOT_SUSPENDED);
Alex Light3ae82532017-07-26 13:59:07 -0700944 }
945 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
946 // cannot tell why resume failed.
947 {
948 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
949 if (target->GetUserCodeSuspendCount() == 0) {
950 return ERR(THREAD_NOT_SUSPENDED);
951 }
952 }
953 }
954 // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
955 // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
956 DCHECK(target != self);
957 if (!art::Runtime::Current()->GetThreadList()->Resume(target,
958 art::SuspendReason::kForUserCode)) {
959 // TODO Give a better error.
960 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
961 return ERR(INTERNAL);
962 } else {
963 return OK;
964 }
965 } while (true);
Alex Light88fd7202017-06-30 08:31:59 -0700966}
967
Alex Light7ddc23d2017-09-22 15:33:41 -0700968static bool IsCurrentThread(jthread thr) {
969 if (thr == nullptr) {
970 return true;
971 }
972 art::Thread* self = art::Thread::Current();
973 art::ScopedObjectAccess soa(self);
974 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
975 art::Thread* target = nullptr;
976 jvmtiError err_unused = ERR(INTERNAL);
977 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
978 return target == self;
979 } else {
980 return false;
981 }
982}
983
Alex Light88fd7202017-06-30 08:31:59 -0700984// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
985// since we can have threads in the list multiple times. This generally doesn't matter unless the
986// current thread is present multiple times. In that case we need to suspend only once and either
987// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
988// it didn't. We also want to handle the current thread last to make the behavior of the code
989// simpler to understand.
990jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
991 jint request_count,
992 const jthread* threads,
993 jvmtiError* results) {
994 if (request_count == 0) {
995 return ERR(ILLEGAL_ARGUMENT);
996 } else if (results == nullptr || threads == nullptr) {
997 return ERR(NULL_POINTER);
998 }
999 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
1000 // running thread. These indexes we need to handle specially since we need to only actually
1001 // suspend a single time.
1002 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -07001003 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -07001004 if (IsCurrentThread(threads[i])) {
1005 current_thread_indexes.push_back(i);
1006 } else {
1007 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -07001008 }
Alex Light88fd7202017-06-30 08:31:59 -07001009 }
1010 if (!current_thread_indexes.empty()) {
1011 jint first_current_thread_index = current_thread_indexes[0];
1012 // Suspend self.
1013 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1014 results[first_current_thread_index] = res;
1015 // Fill in the rest of the error values as appropriate.
1016 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1017 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1018 results[*it] = other_results;
1019 }
1020 }
1021 return OK;
1022}
1023
1024jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1025 jint request_count,
1026 const jthread* threads,
1027 jvmtiError* results) {
1028 if (request_count == 0) {
1029 return ERR(ILLEGAL_ARGUMENT);
1030 } else if (results == nullptr || threads == nullptr) {
1031 return ERR(NULL_POINTER);
1032 }
1033 for (jint i = 0; i < request_count; i++) {
1034 results[i] = env->ResumeThread(threads[i]);
1035 }
1036 return OK;
1037}
1038
Alex Light54d39dc2017-09-25 17:00:16 -07001039jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1040 jthread thread,
1041 jobject exception) {
1042 art::Thread* self = art::Thread::Current();
1043 art::ScopedObjectAccess soa(self);
1044 art::StackHandleScope<1> hs(self);
1045 if (exception == nullptr) {
1046 return ERR(INVALID_OBJECT);
1047 }
1048 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1049 if (!obj->GetClass()->IsThrowableClass()) {
1050 return ERR(INVALID_OBJECT);
1051 }
1052 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001053 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001054 art::Thread* target = nullptr;
1055 jvmtiError err = ERR(INTERNAL);
1056 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001057 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001058 return err;
1059 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001060 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001061 return ERR(THREAD_NOT_ALIVE);
1062 }
1063 struct StopThreadClosure : public art::Closure {
1064 public:
1065 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1066
1067 void Run(art::Thread* me) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1068 // Make sure the thread is prepared to notice the exception.
1069 art::Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(me);
1070 me->SetAsyncException(exception_.Get());
1071 // Wake up the thread if it is sleeping.
1072 me->Notify();
1073 }
1074
1075 private:
1076 art::Handle<art::mirror::Throwable> exception_;
1077 };
1078 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -07001079 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light318afe62018-03-22 16:50:10 -07001080 if (target->RequestSynchronousCheckpoint(&c)) {
Alex Light54d39dc2017-09-25 17:00:16 -07001081 return OK;
1082 } else {
1083 // Something went wrong, probably the thread died.
1084 return ERR(THREAD_NOT_ALIVE);
1085 }
1086}
1087
1088jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1089 art::Thread* self = art::Thread::Current();
1090 art::ScopedObjectAccess soa(self);
1091 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1092 art::Thread* target = nullptr;
1093 jvmtiError err = ERR(INTERNAL);
1094 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1095 return err;
1096 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1097 return ERR(THREAD_NOT_ALIVE);
1098 }
1099 target->Interrupt(self);
1100 return OK;
1101}
1102
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001103} // namespace openjdkjvmti